import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login as loginApi, getUserInfo as getUserInfoApi, logout as logoutApi } from '@/api/auth'
import { message } from 'ant-design-vue'
import i18n from '@/i18n'
import { setToken, removeToken, getToken } from '@/utils/auth'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>(getToken()) // 从localStorage中恢复token
  const userInfo = ref<any>(null)

  // 登录
  const login = async (username: string, password: string) => {
    try {
      const res = await loginApi({ username, password })
      console.log("res", res)
      token.value = res.token
      userInfo.value = {
        userId: res.userId,
        username: res.username,
        realName: res.realName
      }
      setToken(res.token)
      return true
    } catch (error: any) {
      message.error(error.message || i18n.global.t('login.invalidCredentials'))
      return false
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const data = await getUserInfoApi()
      userInfo.value = data
      return data
    } catch (error: any) {
      // 清除token和用户信息
      token.value = ''
      userInfo.value = null
      removeToken()
      // 抛出错误，让路由守卫处理
      throw error
    }
  }

  // 登出
  const logout = async () => {
    try {
      await logoutApi()
    } catch (error: any) {
      message.error(error.message || i18n.global.t('user.logout.failed'))
    } finally {
      token.value = ''
      userInfo.value = null
      removeToken()
    }
  }

  return {
    token,
    userInfo,
    login,
    getUserInfo,
    logout
  }
}) 